package models.dao;

import java.util.ArrayList;
import java.util.List;

import models.User;
import play.Logger;

public class UserDAO {

	public static User getUserById(long id) {
		User ret = null;
		try {
			ret = User.findById(id);
		} catch (Exception ex) {

		}
		return ret;
	}

	public static User getOrCreateUser(String userName) {
		User ret = null;
		try {
			List<User> users = User.all().filter("username", userName).fetch();

			if (users.size() == 1) {
				ret = users.get(0);
			} else {
				ret = new User();
				ret.username = userName;
				ret.passcode = "123";
				ret.valided = 1;
				ret.enableEmail = 0;
				ret.insert();
			}

		} catch (Exception ex) {
			ret = null;
		}
		return ret;

	}

	public static List<User> getRegisteredUser() {
		List<User> ret = new ArrayList<User>();
		try {
			List<User> users = User.all().filter("enableEmail", true).fetch();
			for (User u : users) {
				if (u.valided == 1)
					ret.add(u);
			}

		} catch (Exception ex) {
			Logger.error(ex, "", "");
		}
		return ret;
	}

	public static List<User> getAllUser() {
		return User.findAll();
	}

	public static int count() {
		return User.findAll().size();
	}

	public static User createUser(String username, String passcode,
			boolean valided, boolean enableEmail) {
		User ret = new User();
		ret.username = username;
		ret.passcode = passcode;
		ret.valided = valided ? 1 : 0;
		ret.enableEmail = enableEmail ? 1 : 0;
		ret.insert();
		return ret;
	}

}
